package com.sgcc.ln.pmos.e_ln_order.activity;

import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.github.barteksc.pdfviewer.PDFView;
import com.sgcc.ln.pmos.arouter.order.OrderArouterPath;
import com.sgcc.ln.pmos.common.base.BaseActivity;
import com.sgcc.ln.pmos.common.bean.BaseResponse;
import com.sgcc.ln.pmos.common.bean.ContractPDFBean;
import com.sgcc.ln.pmos.common.bean.EventCenter;
import com.sgcc.ln.pmos.common.http.DownloadUtil;
import com.sgcc.ln.pmos.common.http.HttpInterConst;
import com.sgcc.ln.pmos.common.http.HttpRequestUtils;
import com.sgcc.ln.pmos.common.http.MvcNetCallback;
import com.sgcc.ln.pmos.common.utils.ArguConstant;
import com.sgcc.ln.pmos.common.utils.DateUtils;
import com.sgcc.ln.pmos.common.utils.DialogUtil;
import com.sgcc.ln.pmos.common.utils.UserManager;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.e_ln_order.bean.PeriodPointBean;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


/**
 * 确认订单
 */
@Route(path = OrderArouterPath.ORDER_CONFIRMORDER)
public class ConfirmOrderActivity extends BaseActivity {

    private TitleBar mTitleBar;
    private CheckBox mCheckbox;
    private TextView mCommitOrder;
    private PDFView mPdfView;
    String MsgCode = "";

    @Autowired
    public String mRelationId;

    @Autowired
    public String monthDate;

    //pageFlag == 2
    @Autowired
    public String json;//电量变更的json
    @Autowired
    public boolean isDayparting;//是否分时段

    @Autowired
    public int pageFlag;// 2-议价下单用户确认预览生成，3-电价变更用户确认预览生成，4-电量变更用户填写完电量预览生成


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_confirmorder;
    }

    @Override
    protected void initViews() {
        super.initViews();
        findViewByIds();
    }

    private void findViewByIds() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mCheckbox = (CheckBox) findViewById(R.id.checkbox);
        mCommitOrder = (TextView) findViewById(R.id.commit_order);
        mPdfView = findViewById(R.id.pdfView);
        mTitleBar.setTitle("合同预览");
        mCommitOrder.setText(pageFlag == 2 ? "确认签约" :pageFlag == 4 ? "立即确认" : "立即提交");
        mCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    mCommitOrder.setBackgroundColor(0xff0092FF);
                } else {
                    mCommitOrder.setBackgroundColor(0xffdcdcdc);
                }
            }
        });

        mCommitOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCheckbox.isChecked()) {

                        showMsgPop();
                } else {
                    ToastUtils.showShort("请阅读合同并勾选已阅读后再提交订单");
                }
            }
        });

        geyContractPDF();
    }

    private void showMsgPop() {
        //0是下单，1是合约解除，2是立即提交，3是电量变更，4是电价变更
        DialogUtil.showInputCodeDialog(mContext, pageFlag == 4 ? 3 :pageFlag == 3 ? 4 : 2,
                new DialogUtil.OnInputCodeVerifyCodeListener() {
                    @Override
                    public void onVerifyCode() {
                        if (pageFlag == 2) {
                            //立即确认
                            beforeSubmit(mRelationId);
                        }
                        if (pageFlag == 3) {
                            confirmPriceChange(mRelationId, monthDate);
                        }
                        if (pageFlag == 4) {
                            if (isDayparting) {
                                powerChange(json);
                            } else {
                                powerChange1(json);
                            }
                        }


                    }
                });
    }


    public void beforeSubmit(String relationId) {
        Map<String, Object> params = new HashMap<>();
        params.put("_t", System.currentTimeMillis());
        params.put("relationId", relationId);
        HttpRequestUtils.getInstance().request(params, HttpInterConst.ORDER_IMMEDIATESUBMIT, new MvcNetCallback<BaseResponse>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
            }

            @Override
            public void onResponse(BaseResponse response, int id) {
                super.onResponse(response, id);

                if (response != null) {
                    if (response.isSuccess()) {
                        setResult(10001);
                        finish();
                    } else {
                        if (TextUtils.isEmpty(response.getMsg())) {
                            ToastUtils.showShort(response.getMsg());
                        }
                    }
                }

            }
        });
    }

    //获取pdf合同并预览
    public void geyContractPDF() {
        Map<String, Object> params = new HashMap<>();
        params.put("type", pageFlag);
        if (pageFlag == 2) {
            params.put("relationId", mRelationId);
            params.put("membersUsersName", UserManager.getUserBean().getMemberName());
        }
        if (pageFlag == 3) {

            params.put("relationId", mRelationId);
            params.put("changeDate",  DateUtils.getStrng_to_Times_ymd_3(monthDate));
            params.put("membersUsersName", UserManager.getUserBean().getMemberName());
        }

        if (pageFlag == 4) {
            params.put("relationId", mRelationId);
            params.put("changeDate", TextUtils.isEmpty(monthDate) || monthDate.length() < 8 ? "" : monthDate.substring(0, 7));
            PeriodPointBean periodPointBean = GsonUtils.fromJson(json, PeriodPointBean.class);
            List<String> strings = new ArrayList<>();
            if (isDayparting) {
                strings.add(periodPointBean.getEnergy1());
                strings.add(periodPointBean.getEnergy2());
                strings.add(periodPointBean.getEnergy3());
                strings.add(periodPointBean.getEnergy4());
                strings.add(periodPointBean.getEnergy5());
                strings.add(periodPointBean.getEnergy6());
                strings.add(periodPointBean.getEnergy7());
                strings.add(periodPointBean.getEnergy8());
                strings.add(periodPointBean.getEnergy9());
                strings.add(periodPointBean.getEnergy10());
                strings.add(periodPointBean.getEnergy11());
                strings.add(periodPointBean.getEnergy12());
                strings.add(periodPointBean.getEnergy13());
                strings.add(periodPointBean.getEnergy14());
                strings.add(periodPointBean.getEnergy15());
                strings.add(periodPointBean.getEnergy16());
                strings.add(periodPointBean.getEnergy17());
                strings.add(periodPointBean.getEnergy18());
                strings.add(periodPointBean.getEnergy19());
                strings.add(periodPointBean.getEnergy20());
                strings.add(periodPointBean.getEnergy21());
                strings.add(periodPointBean.getEnergy22());
                strings.add(periodPointBean.getEnergy23());
                strings.add(periodPointBean.getEnergy24());
            } else {
                strings.add(periodPointBean.getEnergy0());
            }
            params.put("changeEnergyList", strings);
        }


        HttpRequestUtils.getInstance().request(params, HttpInterConst.ORDER_GREATCONTRACT,
                new MvcNetCallback<ContractPDFBean>(true) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        super.onError(call, e, id);
                    }

                    @Override
                    public void onResponse(ContractPDFBean response, int id) {
                        super.onResponse(response, id);


                        DownloadUtil.get().downloadPdf(mContext, response.getData(), new DownloadUtil.OnDownloadListener() {
                            @Override
                            public void onDownloadSuccess(File file) {
                                mPdfView.fromFile(file)
                                        .defaultPage(0)
                                        .enableAnnotationRendering(true)
                                        .spacing(10)
                                        .load();
                            }

                            @Override
                            public void onDownloading(int progress) {

                            }

                            @Override
                            public void onDownloadFailed(Exception e) {

                            }
                        });


                    }
                });
    }


    /**
     * 电价变更
     *
     * @param relationId //订单ID
     * @param monthDate  //月份
     */
    public void confirmPriceChange(String relationId, String monthDate) {
        Map<String, Object> params = new HashMap<>();
        params.put("_t", System.currentTimeMillis());
        params.put("relationId", relationId);
        params.put("monthDate", monthDate);
        HttpRequestUtils.getInstance().request(params, HttpInterConst.ORDER_CONFIRMPRICECHANGE,
                new MvcNetCallback<BaseResponse>(true) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        super.onError(call, e, id);

                    }

                    @Override
                    public void onResponse(BaseResponse response, int id) {
                        super.onResponse(response, id);
                        if (response != null) {
                            if ("200".equals(response.getCode())) {
                                setResult(RESULT_OK);
                                finish();

                            } else {
                                if (TextUtils.isEmpty(response.getMsg())) {
                                    ToastUtils.showShort(response.getMsg());
                                }
                            }
                        }
                    }
                });
    }


    /**
     * 电量变更  分时段
     */
    public void powerChange(String json) {
        HttpRequestUtils.getInstance().publicRequest(json,
                HttpInterConst.ORDER_POWERCHANGE, new MvcNetCallback<BaseResponse>(true) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        super.onError(call, e, id);
                    }

                    @Override
                    public void onResponse(BaseResponse response, int id) {
                        super.onResponse(response, id);
                        if (response != null) {
                            if ("200".equals(response.getCode())) {
                                ActivityUtils.finishActivity(DaypartingEleChangesActivity.class);
                                ToastUtils.showShort(response.getMsg());
                                finish();
                            } else {
                                if (TextUtils.isEmpty(response.getMsg())) {
                                    ToastUtils.showShort(response.getMsg());
                                }
                            }
                        }

                    }
                }, null);

    }

    /**
     * 电量变更  不分时段
     */
    public void powerChange1(String json) {
        HttpRequestUtils.getInstance().publicRequest(json, HttpInterConst.ORDER_POWERCHANGE, new MvcNetCallback<BaseResponse>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
            }

            @Override
            public void onResponse(BaseResponse response, int id) {
                super.onResponse(response, id);
                if (response != null) {
                    if (TextUtils.isEmpty(response.getMsg()))
                        ToastUtils.showLong(response.getMsg());
                    if ("200".equals(response.getCode())) {
                        EventBus.getDefault().post(new EventCenter<>(ArguConstant.REFRESH_CONTRACT));
                        ActivityUtils.finishActivity(OrderDetailsActivity.class);
                        ActivityUtils.finishActivity(NoDaypartingEleChangesActivity.class);
                        finish();
                    }
                }

            }
        }, null);
    }
}
